package com.xique.blelock.view.AcountManager;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.Log;

import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.xique.blelock.NetUtils.XqNetClient;
import com.xique.blelock.R;
import com.xique.blelock.Utils.ACache;
import com.xique.blelock.Utils.SettingManager;
import com.xique.blelock.Utils.Stringkey;
import com.xique.blelock.Utils.TimeUtil;
import com.xique.blelock.view.BaseActivity;
import com.xique.blelock.view.Home_Activity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class SplashActivity extends BaseActivity {

    private static final String TAG = SplashActivity.class.getSimpleName();
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splashactivity);
        Log.e(TAG, "设备高度："+  QMUIDisplayHelper.getScreenHeight(this) + "px  宽度："+QMUIDisplayHelper.getScreenWidth(this));

        flash();
    }

    private void flash() {


        if( userInfo != null && (userInfo.getPhonenum() != null)){
//            jumpMainPage();
            //利用token进行登录
            LoginByToken();
        }else{
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent(SplashActivity.this,Login_Activity.class);
                    startActivity(intent);
                    // 侧滑进入下个activity,必须在 StartActivity() 或 finish() 之后立即调用
                    //overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
                    finish();
                }
            }, 2500);
        }

    }


    //token方式登录
    private void LoginByToken(){
        XqNetClient netClient =  new XqNetClient();
        JSONObject body = new JSONObject();
        try {
            body.put(Stringkey.LoginName, userInfo.getPhonenum());
            body.put(Stringkey.Token,userInfo.getToken());
            body.put("type", SettingManager.TOKENTYPE);
            body.put("timestamp", TimeUtil.getSystemCurrentTimeLong()+"");
        } catch (JSONException e) {
            e.printStackTrace();
        }

//        showProgressDialog();
        netClient.Login(body.toString()).enqueue(new Callback<String>() {//TOken方式登录
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if (response.body()!=null && response.body().contains("成功")) {
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(response.body());
                        String dates=jsonObject.getString("data");
                        JSONObject object1 = new JSONObject(dates);
                        String token = object1.getString("token");
                        userInfo.setIssetPwd(object1.getInt(Stringkey.isSetPwd));
                        userInfo.setLogintype(SettingManager.TOKENTYPE);
                        userInfo.setToken(token);
                        ACache.getInstance().put(Stringkey.USERInfo,userInfo);
                        queryUserInfo();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }else{
                    try {
                        showToast(SplashActivity.this, "登录失败："+response.errorBody().string());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
//                hideProgressDialog();
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                t.printStackTrace();
//                hideProgressDialog();

            }
        });
    }

    /**
     * 查询用户信息
     */
    private void queryUserInfo() {
        XqNetClient netClient = new XqNetClient();
        JSONObject jsonobject = new JSONObject();
        try {
            jsonobject.put("token", userInfo.getToken());
            jsonobject.put("uid", userInfo.getUid());
            jsonobject.put("timestamp", TimeUtil.getSystemCurrentTimeLong()+"");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        netClient.queryUserInfo(jsonobject.toString()).enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if(response.body() == null){
                    showToast(SplashActivity.this, "用户信息没有设置");
                    return;
                }
                Log.e(TAG, "-===获取查询用户信息：" + response.body());
                String code = "1";
                String names = "xaio";
                String sexs = "女";
                int age  = 0;
                try {
                    JSONObject jsonObject1 = new JSONObject(response.body());
                    code = jsonObject1.getString("message");
                    String datas = jsonObject1.getString("data");
                    JSONObject jsonObject2 = new JSONObject(datas);
                    names = jsonObject2.getString("name");
                    sexs = jsonObject2.getString("gender");
                    age = jsonObject2.getInt("age");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (code.equals("成功")) {//如果成功就
                    userInfo.setNickname(names);
                    userInfo.setSex(Integer.parseInt(sexs));
                    userInfo.setAge(age);
                    ACache.get(SplashActivity.this).put(Stringkey.USERInfo, userInfo);

                }else if(code.equals(Stringkey.UserNotSetting)){
                    userInfo.setSetting(false);
                    ACache.get(SplashActivity.this).put(Stringkey.USERInfo, userInfo);
                }
                jumpMainPage();
            }
            @Override
            public void onFailure(Call<String> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

    private void  jumpMainPage(){
        //d登录成功，需要设置别名
        Intent serverIntent = new Intent(SplashActivity.this, Home_Activity.class); // 跳转主界面
        startActivity(serverIntent);
        finish();
    }

}
